package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.MyWindowFunction;
import com.atguigu.bean.ExamQuestionBean;
import com.atguigu.util.ClickHouseUtil_hjy;
import com.atguigu.util.MyKafkaUtil_hjy;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hjy
 * @create 2023/3/28 20:51
 */
public class Dws_examQuestionWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://47.102.112.46:8020/gmall-flink/check/baseLogApp");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME","atguigu");
        //todo 2 从kafka主题（dwd_test_exam_question）消费数据
        String topic="dwd_test_exam_question";
        String groupId="dws_exam_question_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil_hjy.getKafkaConsumer(topic, groupId));
        //todo 3 将数据转为JSONObj 并过滤 并提取时间戳
        SingleOutputStreamOperator<JSONObject> jsonObjWithWM = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject record = JSON.parseObject(value);
                out.collect(record);
            }
        })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                return element.getLong("create_time");
                            }
                        })));
        //todo 4 按照uid分组
        KeyedStream<JSONObject, String> keyedByUidDS = jsonObjWithWM.keyBy(value -> value.getString("user_id"));
        //todo 5 转为javaBean
        SingleOutputStreamOperator<ExamQuestionBean> javaBeanWithUidDS = keyedByUidDS.map(new RichMapFunction<JSONObject, ExamQuestionBean>() {
            private ValueState<String> userState;
            private ValueState<String> userCorrectState;

            @Override
            public void open(Configuration parameters) throws Exception {
                userState = getRuntimeContext().getState(new ValueStateDescriptor<String>("user_exist", String.class));
                userCorrectState = getRuntimeContext().getState(new ValueStateDescriptor<String>("correct_user", String.class));
            }

            @Override
            public ExamQuestionBean map(JSONObject value) throws Exception {
                String exist = userState.value();
                String correctUser = userCorrectState.value();
                String isCorrect = value.getString("is_correct");
                Long uv = 0L;
                Long correctUv = 0L;
                Long correctQuestion=0L;
                if (exist == null) {
                    userState.update("1");
                    uv = 1L;
                }
                if (correctUser == null && "1".equals(isCorrect)) {
                    userCorrectState.update("1");
                    correctUv = 1L;
                }
                if ("1".equals(isCorrect)){
                    correctQuestion=1L;
                }
                return ExamQuestionBean.builder()
                        .questionId(value.getString("question_id"))
                        .isCorrect(isCorrect)
                        .correctUvCt(correctUv)
                        .uvCt(uv)
                        .questionCt(1L)
                        .correctQuestionCt(correctQuestion)
                        .build();
            }
        });
        //todo 6 按照题目ID分组
        KeyedStream<ExamQuestionBean, String> keyedByQuestionIdDS = javaBeanWithUidDS.keyBy(ExamQuestionBean::getQuestionId);

        //todo 7 开窗聚合
        SingleOutputStreamOperator<ExamQuestionBean> reduceDS = keyedByQuestionIdDS.window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<ExamQuestionBean>() {
                    @Override
                    public ExamQuestionBean reduce(ExamQuestionBean value1, ExamQuestionBean value2) throws Exception {
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        value1.setCorrectUvCt(value1.getCorrectUvCt() + value2.getCorrectUvCt());
                        value1.setQuestionCt(value1.getQuestionCt() + value2.getQuestionCt());
                        value1.setCorrectQuestionCt(value1.getCorrectQuestionCt() + value2.getCorrectQuestionCt());
                        return value1;
                    }
                }, new WindowFunction<ExamQuestionBean, ExamQuestionBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<ExamQuestionBean> input, Collector<ExamQuestionBean> out) throws Exception {
                        ExamQuestionBean next = input.iterator().next();
                        out.collect(MyWindowFunction.getWindow(next, window));
                    }
                });
        //todo 8 写入数据到clickHouse

        reduceDS.print("reduceDS>>>>>>>>>>>>");
        reduceDS.addSink(ClickHouseUtil_hjy.getClickHouseSink("insert into dws_exam_question_window values(?,?,?,?,?,?,?,?)"));

        //todo 9 启动程序
        env.execute();
    }
}
